<script>
import trafficConfig from './config.js';
import {getGoodsDetail, addEleCouponOrders} from "@/api/mall";

export default {
  name: "buyTickets",
  data() {
    return {
      // 线路数据
      routeInfo: null,
      // 区域和线路ID
      locationId: 2,
      routeId: 1,
      
      // 表单数据
      form: {
        specId: '', // 规格ID
        price: 0,
        quantity: 1
      },
      products: {},
      
      // 价格列表 
      priceList: [],
      
      // 选中的价格索引
      selectedPriceIndex: 0,
      
      // 加载状态
      loading: true,
      
      btnLoading: false
    }
  },
  computed: {
    // 计算总价
    totalPrice() {
      return this.form.price * this.form.quantity;
    }
  },
  onLoad(option) {
    // 获取路由参数中的线路ID和区域ID
    const routeId = parseInt(option.id || '1');
    const locationId = parseInt(option.locationId || '2'); // 默认东澳岛
    this.locationId = locationId;
    this.routeId = routeId;
    console.log('接收到的线路ID:', routeId, '区域ID:', locationId);
    
    // 加载线路数据
    this.getRouteDetail(locationId, routeId);
  },
  methods: {
    // 获取线路详情
    getRouteDetail(locationId, routeId) {
      this.loading = true;
      
      try {
        // 新结构：传入 locationId 和 routeId
        this.routeInfo = trafficConfig.getRouteById(locationId, routeId);
        this.getThePriceOfTheLine();
        console.log('加载线路:', this.routeInfo.name);
        
        this.loading = false;
      } catch (error) {
        console.error("获取线路详情失败:", error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
        this.loading = false;
      }
    },
    
    // 获取线路价格
    getThePriceOfTheLine() {
      if (!this.routeInfo || !this.routeInfo.productId) {
        console.error('没有找到产品ID');
        return;
      }
      
      this.loading = true;
      
      getGoodsDetail({
        Id: this.routeInfo.productId
      }).then(res => {
        if (res && res.Data) {
          const data = res.Data;
          this.products = res.Data
          // 获取价格列表
          if (data.ProductSpecList && data.ProductSpecList.length > 0) {
            this.priceList = data.ProductSpecList.map(item => {
              return {
                id: item.Id,
                name: item.Name || item.SpecsName || '标准票',
                price: item.Price,
                productSpecId: item.Id,
                description: item.Description || '',
                shopId: item.shopId || '',
                merchantID: item.merchantID || '',
                ...item
              };
            });
            
            // 设置默认选中第一个价格
            if (this.priceList.length > 0) {
              this.selectPrice(0);
            }
          } else {
            // 如果没有规格价格，使用默认价格
            this.priceList = [{
              id: '',
              name: '标准票',
              price: this.routeInfo.ticketPrice || 10,
              description: ''
            }];
            this.selectPrice(0);
          }
        }
        
        this.loading = false;
      }).catch(err => {
        console.error("获取价格失败:", err);
        // 使用默认价格
        this.priceList = [{
          id: '',
          name: '标准票',
          price: this.routeInfo.ticketPrice || 10,
          description: ''
        }];
        this.selectPrice(0);
        this.loading = false;
      });
    },
    
    // 选择价格
    selectPrice(index) {
      if (index >= 0 && index < this.priceList.length) {
        this.selectedPriceIndex = index;
        const selectedPrice = this.priceList[index];
        this.form.specId = selectedPrice.id;
        this.form.price = selectedPrice.price;
      }
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.form.quantity > 1) {
        this.form.quantity--;
      }
    },
    
    // 增加数量
    increaseQuantity() {
      this.form.quantity++;
    },
    
    // 提交订单
    async submitOrder() {
      // 验证表单数据
      if (this.selectedPriceIndex === -1) {
        uni.showToast({
          icon: 'none',
          title: '请选择票价'
        });
        return;
      }
      
      // 设置加载状态
      this.btnLoading = true;
      
      try {
        const priceInfo = this.priceList[this.selectedPriceIndex];
        
        // 构建订单参数
        const orderParams = {
          BusinessId: this.products.BusinessId,
          ProductId: this.products.Id,
          ProductSpecId: priceInfo.productSpecId,
          ProductName: `${this.routeInfo.name}-${priceInfo.name}`,
          ProductType: this.products.Type,
          Price: priceInfo.price,
          Count: this.form.quantity,
          PayStatus: 0,
          Point: 0,
          Deposit: 0,
          ContactMobile: '',
          ContactName:  '',
          CouponDiscount: 0,
          OriginalPrice: priceInfo.price,
          PlatformType: 20, // 小程序
          SettleType: 1,
          payType: 0,
          IsTicket: 1, // 电子票
          ShopId: this.products.shopId || 0,
          MerchantId: this.products.MerchantID || 0,
          Persons: []
        };

        console.log(orderParams)
        
        // 构建请求参数
        const requestParams = {
          OrderProductList: [orderParams],
          Coupons: []
        };
        
        // 调用API提交订单
        const { Data } = await addEleCouponOrders(requestParams);
        console.log(Data);
        if(Data.IsPay === 1){
          uni.navigateTo({
            url: `/mall_subpages/goods/payment?id=${Data.OrdersOnLineId}&delta=2`
          });
        }else {
          uni.showToast({
            icon: 'none',
            title: '创建订单失败'
          });
        }

        // if (Data.success) {
        //   // 订单创建成功，跳转到支付页面
        //   uni.redirectTo({
        //     url: `/pages/payment/payment?orderId=${res.data.data.OrderId}&amount=${this.totalPrice}`
        //   });
        // } else {
        //   uni.showToast({
        //     icon: 'none',
        //     title: res.data.message || '创建订单失败'
        //   });
        // }
      } catch (error) {
        console.error("提交订单失败:", error);
        uni.showToast({
          icon: 'none',
          title: '网络异常，请稍后再试'
        });
      } finally {
        this.btnLoading = false;
      }
    },
    
    // 查看交通图
    viewTrafficMap() {
      uni.navigateTo({
        url: '/pages/map/traffic'
      });
    }
  }
}
</script>

<template>
  <view class="buy-tickets-container">
    <!-- 加载中 -->
    <view class="loading-container" v-if="loading">
      <view class="loading-icon"></view>
      <text>加载中...</text>
    </view>
    
    <block v-if="!loading && routeInfo">
      <!-- 线路基本信息 -->
      <view class="route-info-card">
        <view class="route-header">
          <view class="route-name">
            <text class="name">{{routeInfo.name}}</text>
            <text class="subtitle">{{routeInfo.subtitle}}</text>
          </view>
          <view class="view-map" @click="viewTrafficMap">
            <image src="/static/traffic/bus-icon.png" mode="aspectFit"></image>
            <text>查看交通图</text>
          </view>
        </view>
        
        <view class="route-details">
          <text v-if="routeInfo.firstBusTime && routeInfo.lastBusTime">首车 {{routeInfo.firstBusTime}} 末车 {{routeInfo.lastBusTime}} | {{routeInfo.totalTime}}</text>
          <text v-else>{{routeInfo.totalTime || ''}}</text>
        </view>
      </view>
      
      <!-- 价格选择区域 -->
      <view class="ticket-form">
        <view class="section-title">票价选择</view>
        
        <!-- 价格单选 -->
        <view class="price-options">
          <view 
            v-for="(priceItem, index) in priceList" 
            :key="index"
            class="price-option-item"
            :class="{'active': selectedPriceIndex === index}"
            @click="selectPrice(index)"
          >
            <view class="price-option-content">
              <view class="price-name">{{priceItem.name}}</view>
              <view class="price-value">¥ {{priceItem.price}}</view>
              <view class="price-desc" v-if="priceItem.description">{{priceItem.description}}</view>
            </view>
            <view class="price-option-radio">
              <view class="radio-inner" v-if="selectedPriceIndex === index"></view>
            </view>
          </view>
        </view>
        
        <!-- 数量 -->
        <view class="form-item">
          <view class="form-label">数量</view>
          <view class="form-value quantity-control">
            <view class="quantity-btn minus" @click="decreaseQuantity">－</view>
            <view class="quantity-input">{{form.quantity}}</view>
            <view class="quantity-btn plus" @click="increaseQuantity">＋</view>
          </view>
        </view>
        
        <!-- 总价 -->
        <view class="form-item total-price">
          <view class="form-label">总计</view>
          <view class="form-value price-value">
            <text class="price">¥ {{totalPrice}}</text>
          </view>
        </view>
      </view>
      
      <!-- 提交按钮 -->
      <view class="submit-btn-container">
        <view class="submit-btn" @click="submitOrder">
          <text>立即预定</text>
        </view>
      </view>
      
      <!-- 特殊服务说明 -->
      <view class="tips-card" v-if="routeInfo.id === 5 || routeInfo.specialNote">
        <view class="tips-title">预订说明</view>
        <view class="tips-content">
          <text>{{routeInfo.specialNote}}</text>
        </view>
      </view>
      
      <!-- 注意事项 -->
      <view class="tips-card" v-if="routeInfo.notes && routeInfo.notes.length > 0">
        <view class="tips-title">注意事项</view>
        <view class="tips-content">
          <view v-for="(note, index) in routeInfo.notes" :key="index" class="note-item">
            {{note}}
          </view>
        </view>
      </view>
    </block>
  </view>
</template>

<style scoped lang="scss">
.buy-tickets-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

/* 线路信息卡片 */
.route-info-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .route-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20rpx;
    
    .route-name {
      flex: 1;
      
      .name {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .subtitle {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .view-map {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      image {
        width: 50rpx;
        height: 50rpx;
        margin-bottom: 5rpx;
      }
      
      text {
        font-size: 22rpx;
        color: #3a7fe6;
      }
    }
  }
  
  .route-details {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 15rpx;
  }
}

/* 表单样式 */
.ticket-form {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    padding-bottom: 20rpx;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .price-options {
    margin-bottom: 30rpx;
    
    .price-option-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;
      margin-bottom: 15rpx;
      border-radius: 8rpx;
      border: 1px solid #f0f0f0;
      background-color: #f9f9f9;
      transition: all 0.3s ease;
      
      &.active {
        border-color: #3a7fe6;
        background-color: rgba(58, 127, 230, 0.05);
      }
      
      .price-option-content {
        flex: 1;
        
        .price-name {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .price-value {
          font-size: 32rpx;
          color: #ff5f34;
          font-weight: bold;
          margin-bottom: 8rpx;
        }
        
        .price-desc {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .price-option-radio {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        border: 2rpx solid #ddd;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        
        .radio-inner {
          width: 24rpx;
          height: 24rpx;
          border-radius: 50%;
          background-color: #3a7fe6;
        }
      }
      
      &.active .price-option-radio {
        border-color: #3a7fe6;
      }
    }
  }
  
  .form-item {
    display: flex;
    padding: 30rpx 0;
    border-bottom: 1px solid #f0f0f0;
    align-items: center;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.total-price {
      border-top: 1px dashed #f0f0f0;
      padding-top: 40rpx;
      margin-top: 10rpx;
      
      .price {
        font-size: 36rpx !important;
      }
    }
    
    .form-label {
      width: 120rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    .form-value {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      text {
        font-size: 28rpx;
        color: #333;
      }
      
      .arrow-icon {
        width: 36rpx;
        height: 36rpx;
      }
      
      &.price-value {
        .price {
          color: #ff5f34;
          font-weight: bold;
        }
      }
    }
    
    .quantity-control {
      display: flex;
      align-items: center;
      
      .quantity-btn {
        width: 60rpx;
        height: 60rpx;
        border: 1px solid #ddd;
        border-radius: 4rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        color: #333;
        background-color: #f8f8f8;
        
        &.minus {
          color: #999;
        }
      }
      
      .quantity-input {
        width: 100rpx;
        height: 60rpx;
        border-top: 1px solid #ddd;
        border-bottom: 1px solid #ddd;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

/* 提交按钮 */
.submit-btn-container {
  padding: 30rpx 0;
  
  .submit-btn {
    height: 90rpx;
    background: linear-gradient(90deg, #3a7fe6, #5895e9);
    border-radius: 45rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 15rpx rgba(58, 127, 230, 0.3);
    
    text {
      font-size: 32rpx;
      color: #fff;
      font-weight: 500;
    }
  }
}

/* 提示卡片 */
.tips-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .tips-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 15rpx;
    position: relative;
    padding-left: 20rpx;
    
    &:before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 8rpx;
      height: 30rpx;
      background-color: #3a7fe6;
      border-radius: 4rpx;
    }
  }
  
  .tips-content {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
    
    .note-item {
      margin-bottom: 10rpx;
      padding-left: 20rpx;
      position: relative;
      
      &:before {
        content: '•';
        position: absolute;
        left: 0;
        top: 0;
      }
    }
  }
}

/* 加载状态 */
.loading-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .loading-icon {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #3a7fe6;
    border-radius: 50%;
    animation: rotate 1s linear infinite;
  }
  
  text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>